import styles from './index.module.scss'
import ArticleItem from '../ArticleItem'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList } from '@/store/actions/home'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile'
import { RootType } from '@/store'
/**
 * 文章列表组件
 * @param {String} props.channelId 当前文章列表所对应的频道ID
 * @param {String} props.aid 当前 Tab 栏选中的频道ID
 */
type Props = {
  channelId: number
  aid: number
}
const ArticleList = ({ channelId, aid }: Props) => {
  // 列表数据
  const current = useSelector((state: RootType) => state.home.articles[channelId])
  // 控制是否继续加载
  const [hasMore, setHasMore] = useState(true)
  // 控制加载状态
  const [loading, setLoading] = useState(false)
  // console.log(current);
  const { list } = current || []
  const dispatch = useDispatch()
  // 下拉刷新
  const onRefresh = async () => {
    await dispatch(getArticleList(channelId, Date.now() + '') as any)
    setHasMore(true)
  }
  // 上拉加载更多
  const loadMore = async () => {
    if (loading) return
    if (channelId !== aid) setLoading(true)
    if (!current.timestamp) {
      setHasMore(false)
      return
    }
    try {
      await dispatch(getArticleList(channelId, current.timestamp, true) as any)
    } finally {
      setLoading(false)
    }
    // console.log('上拉加载更多');
  }
  useEffect(() => {
    // 发请求要在一个新的函数里面，不能直接在useEffect里面发请求
    // 如果这一页请求过有数据，就不用重新请求数据
    if (current) return
    if (aid === channelId) {
      dispatch(getArticleList(channelId, Date.now() + '') as any)
    }
  }, [channelId, aid, dispatch, current])

  if (!current) return null
  return (
    <div className={styles.root}>
      <div className="articles">
        <PullToRefresh onRefresh={onRefresh}>
          {list.map((item) => (
            <div className="article-item" key={item.art_id}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          ))}
        </PullToRefresh>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default ArticleList
